package com.tzbank.wisdom.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.tzbank.entity.mpass.DeviceBindInfo;
import com.tzbank.esb.util.EsbConsumerUtil;
import com.tzbank.mpass.MpassPushUtils;
import com.tzbank.mpass.enums.DeliveryType;
import com.tzbank.mpass.model.BindAppReq;
import com.tzbank.mpass.model.PushSimpleReq;
import com.tzbank.mpass.model.ReportAppReq;
import com.tzbank.mpass.util.HttpClientUtil;
import com.tzbank.redis.RedisUtils;
import com.tzbank.utils.CodeUtil;
import com.tzbank.utils.ResultCode;
import com.tzbank.utils.ResultUtil;
import com.tzbank.utils.StringConstantUtil;
import com.tzbank.utils.TokenUtil;
import com.tzbank.wisdom.consumer.CommonServiceScheduler;
import com.tzbank.wisdom.entity.SingleDeviceLogin;
import com.tzbank.wisdom.service.CommonService;
import com.tzbank.wisdom.service.DeviceBindInfoService;
import com.tzbank.wisdom.service.IbsaccessLogService;
import com.tzbank.wisdom.service.SingleDeviceLoginService;
import com.tzbank.wisdom.service.UserService;
import com.tzbank.wisdom.utils.BusinessConstant;
import com.tzbank.wisdom.utils.BusinessTypeEnum;
import com.tzbank.wisdom.utils.LoginTypeEnum;
import com.tzbank.wisdom.utils.RequestMap;
import com.tzbank.wisdom.utils.TransCodeEnum;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

@Service(value = "userService")
@Slf4j
public class UserServiceImpl implements UserService {

	@Autowired
	private Environment environment;

	@Resource
	private SingleDeviceLoginService singleDeviceLoginService;

	@Resource
	private IbsaccessLogService ibsaccessLogService;

	@Resource
	private CommonServiceScheduler commonServiceScheduler;

	@Resource
	private DeviceBindInfoService deviceBindInfoService;

	@Resource
	private CommonService commonService;

	@Override
	public Map<String, Object> automaticRegister(Map<String, String> reqBody, Map<String, Object> queryMap) {
		log.info("网银账户首次登录智脑平台后自动注册账户。 请求参数:{}, reqBody:{} , eUserNo:{}", JSON.toJSONString(reqBody), JSON.toJSONString(queryMap));
		
		Map<String, Object> inputMap = new HashMap<String, Object>();
		Map<String, Object> reqSysHead = new HashMap<String, Object>();
		String password = reqBody.get("password");
		String eUserNo = (String) queryMap.get("userNo");
		String eClientNo = (String) queryMap.get("eClientNo");
		
		reqSysHead = RequestMap.getReqSysHead(TransCodeEnum.TRANS_AUTOMATIC_REGISTER.getServiceCode(), TransCodeEnum.TRANS_AUTOMATIC_REGISTER.getServiceSence(), "0110");
		
		Map<String, Object> body = new HashMap<String, Object>();
		body.putAll(reqBody);
		
		inputMap = RequestMap.getInputMap(body);
		
		inputMap.put("sysHead", reqSysHead);
		inputMap.put("eClientNo", eClientNo);  
		inputMap.put("password", password);
		inputMap.put("eUserNo", eUserNo);
		
		log.info("网银账户首次登录智脑平台后自动注册账户 请求开始...");
		Map<String, Object> result = EsbConsumerUtil.clientRequest(inputMap); 
		log.info("网银账户首次登录智脑平台后自动注册账户 请求结束. 响应结果:" + result);
		
		String code = result.get("code").toString();
		JSONObject dataLogin = new JSONObject();
		if (!"".equals(result.get("data"))) {
			 dataLogin = JSONObject.fromObject(result.get("data"));
		}
		
		String logonId = (String) queryMap.get("logonId");
		dataLogin.element("userSeqNo", eUserNo);
		dataLogin.element("clientSeqNo", eClientNo);
		dataLogin.element("clientSeqNo", eClientNo);
		dataLogin.element("logonId", logonId);
		
		result.put("data", dataLogin);
		ibsaccessLogService.add(reqBody, result);// 添加日志
		
		if (!CodeUtil.CODE_200.getCode().equals(code)) {
			switch (code) {
			case BusinessConstant.FIRST_LOGIN_CODE:
				result.put("code", CodeUtil.CODE_10007.getCode());
				break;
			default:
				result.put("code", CodeUtil.CODE_99999.getCode());
				break;
			}
			return result;
		}
		
		String token = TokenUtil.getGeneratePassword();
		dataLogin.element("token", token);
		Long redisAaaa = environment.getProperty("redis.maxInactiveIntervalInSeconds", Long.class);
		RedisUtils.setKeyAndCacheTime(StringConstantUtil.TOKEN + eClientNo, token, redisAaaa);
		RedisUtils.setKeyAndCacheTime(StringConstantUtil.USER + eClientNo, JSON.toJSONString(dataLogin), redisAaaa);
		dataLogin.remove("head");
		dataLogin.element("sameFlag", 0);
		result.put("data", dataLogin);
		
		return ResultUtil.resultMap("自动注册成功", ResultCode.RESULT_CODE_SUCCESS.code(), result.get("data"));
	}
	
	/**
	 * 登录接口
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> logon(Map<String, String> reqBody) {
		String loginType = reqBody.get("loginType");
		if (LoginTypeEnum.TRADITION_LOGIN.getCode().equals(loginType)) {
			String logonId = reqBody.get("logonId");// 可以是用户名 身份证 账号
			String password = reqBody.get("password");
			if (StringUtils.isBlank(logonId)) {
				return ResultUtil.resultMap("请输入账号", CodeUtil.CODE_10000.getCode(), null);
			}
			if (StringUtils.isBlank(password) ) {
				return ResultUtil.resultMap("请输入密码", CodeUtil.CODE_10000.getCode(), null);
			}
		}

		// 查询客户号信息
		log.info("用户登录请求：查询客户号开始 ...");
		Map<String, Object> result = this.queryUserNo(reqBody);
		if (!CodeUtil.CODE_200.getCode().equals(result.get("code"))) {
			log.info("查询客户号结束 响应结果:{}", result.get("msg"));
			return result;
		}

		Map<String, Object> queryMap = (Map<String, Object>) result.get("data");
		queryMap.remove("head");
		
		//自动注册
		if ("1".equals(queryMap.get("openFlag"))) {
			log.info("查询客户号结束 开始自动注册...");
			Map<String, Object> registerMap = this.automaticRegister(reqBody, queryMap);
			log.info("用户登录结束 响应结果: {}", registerMap);
			return registerMap;
		}
		
		// 声明是否是自己调用登陆
		reqBody.put("isAuto", "false");
		// 用户登录
		log.info("查询客户号结束 开始登录...");
		Map<String, Object> loginRes = this.login(reqBody, queryMap);
		log.info("用户登录结束 响应结果: {}", loginRes);

		return loginRes;

	}

	/**
	 * 查询客户号
	 */
	@Override
	public Map<String, Object> queryUserNo(Map<String, String> reqBody) {
		log.info("用户登录 查询客户号 请求参数:{} ", JSON.toJSONString(reqBody));
		
		Map<String, Object> inputMap = new HashMap<String, Object>();
		Map<String, Object> reqSysHead = new HashMap<String, Object>();

		String logonId = reqBody.get("logonId");// 可以是用户名 身份证 账号
		String deviceId = reqBody.get("deviceId");
		String loginType = reqBody.get("loginType");
		
		reqSysHead = RequestMap.getReqSysHead(TransCodeEnum.TRANS_QUERY_LOGIN.getServiceCode(), TransCodeEnum.TRANS_QUERY_LOGIN.getServiceSence(), "0110");
		
		Map<String, Object> body = new HashMap<String, Object>();
		body.putAll(reqBody);
		
		// 调用核心计价因子入参
		inputMap = RequestMap.getInputMap(body);
		
		inputMap.put("sysHead", reqSysHead);
		inputMap.put("logonId", logonId); // 登录名
		inputMap.put("queryFlag", "");
		
		if (LoginTypeEnum.NOT_TRADITION_LOGIN.getCode().equals(loginType)) {
			inputMap.put("equipmentCode", deviceId);
		}

		Map<String, Object> result = EsbConsumerUtil.clientRequest(inputMap); // 查询客户号结果
		String code = result.get("code").toString();
		if (!CodeUtil.CODE_200.getCode().equals(code)) {
			if (BusinessConstant.LOGIN_PASSWORD_NOT_EXIST.equals(code)) {
				result.put("code", CodeUtil.CODE_10012.getCode());
			}
			if (BusinessConstant.LOGIN_PASSWORD_ARGUMENT_ERROR.equals(code)) {
				result.put("code", CodeUtil.CODE_10000.getCode());
			}
			if (BusinessConstant.RESET_PASSWORD_LOGINID_INVALID.equals(code)) {
				result.put("code", CodeUtil.CODE_10014.getCode());
			}
			return result;
		}
		return ResultUtil.resultMap("查询客户号成功", ResultCode.RESULT_CODE_SUCCESS.code(), result.get("data"));

	}

	/**
	 * 用户登录
	 */
	@Override
	public Map<String, Object> login(Map<String, String> reqBody, Map<String, Object> queryMap) {

		Map<String, Object> inputMap = new HashMap<String, Object>();
		Map<String, Object> reqSysHead = new HashMap<String, Object>();
		
		String userSeqNo = queryMap.get("userNo").toString();
		String clientSeqNo = queryMap.get("eClientNo").toString();
		
		String password = reqBody.get("password");
		String deviceId = reqBody.get("deviceId");
		
		String loginType = reqBody.get("loginType");

		reqSysHead = RequestMap.getReqSysHead(TransCodeEnum.TRANS_LOGIN.getServiceCode(), TransCodeEnum.TRANS_LOGIN.getServiceSence(), "0110");
		
		Map<String, Object> body = new HashMap<String, Object>();
		body.putAll(reqBody);
		
		// 调用核心计价因子入参
		inputMap = RequestMap.getInputMap(body);
		
		inputMap.put("sysHead", reqSysHead);
		inputMap.put("logonId", clientSeqNo);// 电子渠道客户号登陆
		inputMap.put("queryFlag", "E");

		inputMap.put("logonMode", "E");
		inputMap.put("passwordType", "E");
		inputMap.put("password", password);
		
		
		inputMap.put("eClientNo", clientSeqNo);
		inputMap.put("eUserNo", userSeqNo);
		
		if (LoginTypeEnum.NOT_TRADITION_LOGIN.getCode().equals(loginType)) {
			inputMap.put("equipmentCode", deviceId);
			inputMap.put("password", "password");
		}
		
		Map<String, Object> loginResult = EsbConsumerUtil.clientRequest(inputMap);
		if (StringUtils.isBlank(loginResult.get("data").toString())) {
			loginResult.put("data", new JSONObject());
		}

		JSONObject dataLogin = JSONObject.fromObject(loginResult.get("data"));
		if (!CodeUtil.CODE_200.getCode().equals(loginResult.get("code"))) {
			// 失败的情况下 客户信息赋值
			dataLogin.element("userSeqNo", userSeqNo);
			dataLogin.element("clientSeqNo", clientSeqNo);
			dataLogin.element("logonId", queryMap.get("logonId"));
			
			loginResult.put("data", dataLogin);
			// 添加日志
			ibsaccessLogService.add(reqBody, loginResult);

			String code = (String) loginResult.get("code");
			switch (code) {
			case BusinessConstant.FIRST_LOGIN_CODE:
				// 首次登陆
				loginResult.put("code", CodeUtil.CODE_10007.getCode());
				break;
			case BusinessConstant.LOGIN_PASSWORD_ERROR_ONE:
				// 密码输入不正确
				loginResult.put("code", CodeUtil.CODE_10004.getCode());
				break;
			case BusinessConstant.LOGIN_PASSWORD_ERROR_WRONG:
				// 登录密码输入错误，还剩下 n 次
				loginResult.put("code", CodeUtil.CODE_10004.getCode());
				break;
			case BusinessConstant.LOGIN_PASSWORD_ERROR_LOCKING:
				// 密码输入错误6次 用户被锁定
				loginResult.put("code", CodeUtil.CODE_10009.getCode());
				break;
			case BusinessConstant.LOGIN_PASSWORD_ERROR_LOCKING_AFTER:
				// 密码被锁定之后
				loginResult.put("code", CodeUtil.CODE_10009.getCode());
				break;
			default:
				loginResult.put("code", CodeUtil.CODE_99999.getCode());
				break;
			}

			return loginResult;
		}

		dataLogin.remove("head");

		// 生成token
		String token = TokenUtil.getGeneratePassword();
		dataLogin.element("token", token);
		Long redisAaaa = environment.getProperty("redis.maxInactiveIntervalInSeconds", Long.class);
		RedisUtils.setKeyAndCacheTime(StringConstantUtil.TOKEN + clientSeqNo, token, redisAaaa);
		loginResult.put("data", dataLogin);

		// 添加日志
		ibsaccessLogService.add(reqBody, loginResult);

		// 判断是否是同设备登录
		int sameFlag = 0;
		if ("false".equals(reqBody.get("isAuto"))) {
			sameFlag = this.isDeviceLogin(reqBody, loginResult);
		}
		JSONObject dataLoginJson = (JSONObject) loginResult.get("data");
		dataLoginJson.element("sameFlag", sameFlag);
		dataLoginJson.remove("password");
		
		RedisUtils.setKeyAndCacheTime(StringConstantUtil.USER + clientSeqNo, JSON.toJSONString(dataLoginJson),
				redisAaaa);
		
		//dataLoginJson.remove("acctArray");
		loginResult.put("data", dataLoginJson);
		log.info("{} 用户登录成功.", clientSeqNo);
		return loginResult;
	}

	/**
	 * 判断是否是不同设备
	 */
	@Transactional
	@Override
	public int isDeviceLogin(Map<String, String> reqBody, Map<String, Object> loginResult) {

		int sameFlag = 0; // 默认是相同设备

		JSONObject dataLogin = (JSONObject) loginResult.get("data");
		String userId = dataLogin.getString("clientSeqNo");
		String deviceId = reqBody.get("deviceId");

		List<SingleDeviceLogin> userList = singleDeviceLoginService.findByUserIdList(userId);

		// 获取最后一次登录的数据信息
		SingleDeviceLogin s = singleDeviceLoginService.findByUserId(userId);

		if (userList.size() > 1) {
			for (SingleDeviceLogin si : userList) {
				if (!si.getRecordId().equals(s.getRecordId())) {
					singleDeviceLoginService.deleteSingleDeviceLogin(si.getRecordId(), si.getUserId(), si.getToken());
				}
			}
		}

		singleDeviceLoginService.addSingleDeviceLogin(s == null ? "0" : s.getRecordId(), reqBody, loginResult);

		if (s != null) {
			if (s.getDeviceId() != null) {
				if (!s.getDeviceId().equals(deviceId)) {
					sameFlag = 1;
					// 推送消息
					Map<String, Object> addMagMap = this.addPushMsg(reqBody, userId);
					if (CodeUtil.CODE_200.getCode().equals(addMagMap.get("code"))) {
						log.info("保存推送消息记录成功：" + addMagMap);
					} else {
						log.info("保存推送消息记录失败：" + addMagMap);
					}
				}
			}
		}

		return sameFlag;
	}

	// TODO 绑定请求
	private Map<String, Object> bindReq(Map<String, String> reqBody, String userId) {
		Map<String, Object> bindMap = new HashMap<>();
		bindMap.put("success", true);
		bindMap.put("message", "绑定成功");

		String flag = "成功: ";

		String deviceType = reqBody.get("deviceType");
		String deviceId = reqBody.get("deviceId");

		BindAppReq bindAppReq = new BindAppReq();
		bindAppReq.setDeliveryToken(deviceId);
		bindAppReq.setUserId(userId);
		bindAppReq.setAppId(deviceId);
		if (BusinessConstant.USER_DEVICE_TYPE_IOS.equalsIgnoreCase(deviceType)) {
			bindAppReq.setOsType(2);
		} else {
			bindAppReq.setOsType(1);
		}

		log.info("绑定请求 请求参数：" + com.alibaba.fastjson.JSONObject.toJSONString(bindAppReq));
		try {
			HttpClientUtil.HttpInvokeResult bindAppResult = MpassPushUtils.bindApp(bindAppReq);
			if (bindAppResult.getCode() != 200) {
				bindMap.put("success", false);
				bindMap.put("message", "绑定请求失败:" + bindAppResult);
				flag = "失败: ";
			}
			log.info("===============绑定请求 " + flag + bindAppResult);

		} catch (Exception e) {
			bindMap.put("success", false);
			bindMap.put("message", "绑定请求失败，出现异常：" + e.getMessage());
			e.printStackTrace();
		}

		return bindMap;
	}

	// TODO 设备上报
	private Map<String, Object> report(Map<String, String> reqBody) {

		Map<String, Object> reportMap = new HashMap<>();
		reportMap.put("success", true);
		reportMap.put("message", "设备上报成功");

		String flag = "成功: ";

		String version = reqBody.get("version");
		String network = reqBody.get("network");
		String deviceId = reqBody.get("deviceId");
		
		//String channel = reqBody.get("version");
		//String imei = reqBody.get("version");
		//String imsi = reqBody.get("version");
		//String model = reqBody.get("version");

		ReportAppReq reportAppReq = new ReportAppReq();
		reportAppReq.setAppVersion(version);
		reportAppReq.setConnectType(network);
		reportAppReq.setDeliveryToken(deviceId);

		reportAppReq.setChannel("channel");
		reportAppReq.setImei("imei");
		reportAppReq.setImsi("imsi");
		reportAppReq.setModel("model");
		reportAppReq.setOsType("2"); // IOS

		log.info("设备上报请求 请求参数：" + com.alibaba.fastjson.JSONObject.toJSONString(reportAppReq));
		try {
			HttpClientUtil.HttpInvokeResult reportAppResult = MpassPushUtils.reportApp(reportAppReq);
			if (reportAppResult.getCode() != 200) {
				reportMap.put("success", false);
				reportMap.put("message", "设备上报请求失败：" + reportAppResult);
				flag = "失败: ";
			}
			log.info("===============设备上报请求 " + flag + reportAppResult);

		} catch (Exception e) {
			reportMap.put("success", false);
			reportMap.put("message", "设备上报请求失败，出现异常：" + e.getMessage());
			e.printStackTrace();
		}
		return reportMap;
	}

	// TODO 推送消息
	private Map<String, Object> push(Map<String, String> reqBody, JSONObject configJson, String userId) {

		Map<String, Object> pushMap = new HashMap<>();
		pushMap.put("success", true);
		pushMap.put("message", "消息推送成功");

		String flag = "成功: ";

		String deviceType = reqBody.get("deviceType");
		String deviceId = reqBody.get("deviceId");

		// 推送消息
		PushSimpleReq pushSimpleReq = new PushSimpleReq();
		pushSimpleReq.setTaskName(configJson.get("taskName").toString());
		pushSimpleReq.setTitle(configJson.get("title").toString());
		pushSimpleReq.setContent(configJson.get("content").toString());
		pushSimpleReq.setExpiredSeconds(900);

		Map<String, String> target = new HashMap<String, String>();
		target.put(deviceId, BusinessTypeEnum.SINGLE_DEVICE_LOGIN.getValue());
		pushSimpleReq.setTarget_msgkey(target);

		pushMap.put("target_msgkey", com.alibaba.fastjson.JSONObject.toJSONString(target));

		if (BusinessConstant.USER_DEVICE_TYPE_ANDROID.equalsIgnoreCase(deviceType)) {
			pushSimpleReq.setDeliveryType(DeliveryType.DEVICE_ANDROID.getValue());
		} else {
			pushSimpleReq.setDeliveryType(DeliveryType.DEVICE_IOS.getValue());
			// TODO 上报
			/*Map<String, Object> reportMap = this.report(reqBody);
			if (!(boolean) reportMap.get("success")) {
				return reportMap;
			}*/
		}

		log.info("消息推送请求 请求参数：" + com.alibaba.fastjson.JSONObject.toJSONString(pushSimpleReq));
		try {
			HttpClientUtil.HttpInvokeResult httpInvokeResult = MpassPushUtils.pushSimple(pushSimpleReq);
			if (httpInvokeResult.getCode() == 200) {
				String result = httpInvokeResult.getResult();
				com.alibaba.fastjson.JSONObject resJson = com.alibaba.fastjson.JSONObject.parseObject(result);
				String reString = resJson.get("success").toString();
				if (!"true".equals(reString)) {
					// TODO 推送失败信息
					pushMap.put("success", false);
					pushMap.put("message", resJson.getString("message"));
					flag = "失败： ";
				}
			} else {
				pushMap.put("success", false);
				pushMap.put("message", "消息推送失败：" + httpInvokeResult);
				flag = "失败： ";
			}
			log.info("===============消息推送请求 " + flag + httpInvokeResult);

		} catch (Exception e) {
			pushMap.put("success", false);
			pushMap.put("message", "消息推送失败，出现异常：" + e.getMessage());
			e.printStackTrace();
		}

		return pushMap;
	}

	/**
	 * 推送消息
	 * 
	 * @param reqBody
	 * @return
	 */
	public Map<String, Object> addPushMsg(Map<String, String> reqBody, String userId) {

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("success", true);
		resultMap.put("message", "消息推送成功");

		String deviceType = reqBody.get("deviceType");
		String deviceId = reqBody.get("deviceId");

		Map<String, Object> queryMap = new HashMap<>();
		queryMap.put("businessType", BusinessTypeEnum.SINGLE_DEVICE_LOGIN.getValue());

		Map<String, Object> queryRes = commonServiceScheduler.findByBusinessType(queryMap);
		if (!CodeUtil.CODE_200.getCode().equals(queryRes.get("code"))) {
			return ResultUtil.resultMap(queryRes.get("msg").toString(), ResultCode.RESUTL_CODE_FAILURE.code(),
					queryRes.get("data"));
		}

		JSONObject queryJson = JSONObject.fromObject(queryRes.get("data"));
		JSONObject configJson = (JSONObject) queryJson.get("pushMsgConfig");

		int flag = 0;
		DeviceBindInfo info = deviceBindInfoService.findByDeviceId(userId, deviceId, deviceType);
		// 判断是否已经有绑定过设备信息，若绑定过则不再绑定，没有则绑定。 TODO
		if (info == null) {
			Map<String, Object> bindMap = this.bindReq(reqBody, userId);
			if ((boolean) bindMap.get("success")) {
				this.addDeviceBindInfo(reqBody, userId);// 添加绑定信息
			} else {
				resultMap.put("success", false);
				resultMap.put("message", bindMap.get("message"));
				flag = 1;
			}
		}

		String target_msgkey = "";
		if (flag == 0) {
			// TODO 消息推送
			Map<String, Object> pushMap = this.push(reqBody, configJson, userId);
			if (!(boolean) pushMap.get("success")) {
				resultMap.put("success", false);
				resultMap.put("message", pushMap.get("message"));
			}

			target_msgkey = pushMap.get("target_msgkey").toString();
		}

		Map<String, Object> msgMap = new HashMap<>();

		msgMap.put("taskName", configJson.get("taskName"));
		msgMap.put("title", configJson.get("title"));
		msgMap.put("content", configJson.get("content"));
		msgMap.put("uri", configJson.get("uri"));
		msgMap.put("expiredSeconds", configJson.get("expiredSeconds"));
		msgMap.put("msgType", configJson.get("msgType"));
		msgMap.put("showMode", configJson.get("showMode"));
		msgMap.put("pushTag", configJson.get("pushTag"));
		msgMap.put("pushObject", configJson.get("pushObject"));

		// TODO 目标key 暂时不清楚
		msgMap.put("targetMsgkey", target_msgkey);

		// TODO 消息推送状态 0-未推送 1-推送成功 2-推送失败
		if ((boolean) resultMap.get("success")) {
			msgMap.put("pushState", "1");
		} else {
			msgMap.put("pushState", "2");
		}

		String message = resultMap.get("message").toString();
		msgMap.put("remark", message);
		msgMap.put("templateId", "");

		msgMap.put("readStatus", "0");
		msgMap.put("pushDate", new Date());

		if (BusinessConstant.USER_DEVICE_TYPE_IOS.equalsIgnoreCase(deviceType)) {
			msgMap.put("deliveryType", DeliveryType.DEVICE_IOS.getValue());
		} else {
			msgMap.put("deliveryType", DeliveryType.DEVICE_ANDROID.getValue());
		}

		// 插入模板消息
		Map<String, Object> addTempMap = commonServiceScheduler.addMsgTemplate(msgMap);
		String data = JSONUtils.toJSONString(addTempMap.get("data"));

		String code = addTempMap.get("code").toString();
		if (!CodeUtil.CODE_200.getCode().equals(code)) {
			log.info("插入消息模板表数据失败...");
			return addTempMap;
		}
		com.alibaba.fastjson.JSONObject tempJson = com.alibaba.fastjson.JSONObject.parseObject(data);
		if (!(boolean) tempJson.get("success")) {
			log.info("插入消息模板表数据失败...");
			return addTempMap;
		}

		// 插入单设备登录发生消息数据
		msgMap.put("templateId", tempJson.get("templateId"));
		Map<String, Object> addMsgMap = commonServiceScheduler.addPushReqMsg(msgMap);

		// 发送验证码
		// reqBody.put("mobile", value)
		// mCSendMsgToMBService.sendMsgToMB(reqBody);

		return addMsgMap;
	}

	/**
	 * 添加设备信息
	 * 
	 * @param reqBody
	 * @param userId
	 */
	public void addDeviceBindInfo(Map<String, String> reqBody, String userId) {
		String deviceType = reqBody.get("deviceType");
		String deviceId = reqBody.get("deviceId");
		DeviceBindInfo info = new DeviceBindInfo();
		info.setUserId(userId);
		info.setDeviceId(deviceId);
		info.setDeviceType(deviceType);
		info.setBindDate(new Date());
		boolean res = deviceBindInfoService.add(info);
		String flag = "失败";
		if (res) {
			flag = "成功";
		}
		log.info("添加设备绑定信息数据：" + flag);
	}

	/**
	 * 修改密码
	 */
	@Override
	public Map<String, Object> resetPassword(Map<String, String> reqBody, int flag) {
		log.info("修改密码请求参数:{}", JSON.toJSONString(reqBody));

		Map<String, Object> inputMap = new HashMap<String, Object>();
		Map<String, Object> reqSysHead = new HashMap<String, Object>();

		String clientSeqNo = reqBody.get("clientSeqNo").toString();
		String userSeqNo = reqBody.get("userSeqNo").toString();
		String logonId = reqBody.get("logonId").toString();
		String newPassword = reqBody.get("passwordNew").toString();
		
		reqSysHead = RequestMap.getReqSysHead(TransCodeEnum.RESET_PASSWORD.getServiceCode(), TransCodeEnum.RESET_PASSWORD.getServiceSence(), "0110");
		
		Map<String, Object> body = new HashMap<String, Object>();
		body.putAll(reqBody);
		
		inputMap = RequestMap.getInputMap(body);
		if (flag == 1) {
			Map<String, Object> userMap = RequestMap.getInputUserInfo(clientSeqNo);
			if (userMap.get("clientNo")==null) {
				return userMap;
			}
			inputMap.putAll(userMap);
		}
		
		inputMap.put("sysHead", reqSysHead);
		inputMap.put("logonId", logonId);
		inputMap.put("eUserNo", userSeqNo);
		inputMap.put("eClientNo", clientSeqNo);
		
		inputMap.put("logonFlag", "2");
		inputMap.put("pwdCheckFlag", "1");

		inputMap.put("newPassword", newPassword);
		inputMap.put("oldPassword", "");
		// 不强制修改
		if (flag == 1) {
			inputMap.put("logonFlag", "1"); //非强制
			inputMap.put("oldPassword", reqBody.get("oldPassword"));
		}

		Map<String, Object> resetResult = EsbConsumerUtil.clientRequest(inputMap);
		String code = resetResult.get("code").toString();
		if (!CodeUtil.CODE_200.getCode().equals(code)) {
			switch (code) {
			case BusinessConstant.RESET_PASSWORD_EXCEPTION:
				resetResult.put("code", CodeUtil.CODE_10010.getCode());
				break;
			case BusinessConstant.RESET_PASSWORD_LOGINID_NOT_EXIST:
				resetResult.put("code", CodeUtil.CODE_10011.getCode());
				break;
			case BusinessConstant.LOGIN_PASSWORD_CIF_CHANNEL_STATE_ERROR:
				resetResult.put("code", CodeUtil.CODE_10013.getCode());
				break;
			default:
				resetResult.put("code", CodeUtil.CODE_99999.getCode());
				break;
			}
			return resetResult;
		}

		Map<String, Object> queryMap = new HashMap<>();
		queryMap.put("eClientNo", clientSeqNo);
		queryMap.put("userNo", inputMap.get("eUserNo"));

		reqBody.put("password", newPassword);
		reqBody.put("isAuto", "true");
		reqBody.put("loginType", "1");//传统登录
		
		//强制修改密码
		if (flag == 0) {
			log.info("修改密码成功 自从登录开始...");
			 Map<String, Object> loginRes = this.login(reqBody, queryMap);
			log.info("修改密码成功 自从登录结束...");
			return loginRes;
		}
		JSONObject dataRes = JSONObject.fromObject(resetResult.get("data"));
		dataRes.remove("head");
		log.info("修改密码成功...");
		resetResult.put("data", dataRes);
		return resetResult;

	}

	/**
	 * 找回密码
	 */
	@Override
	public Map<String, Object> retrievePassword(Map<String, String> reqBody) {
		log.info("找回密码请求参数:{}", JSON.toJSONString(reqBody));

		Map<String, Object> inputMap = new HashMap<String, Object>();
		Map<String, Object> reqSysHead = new HashMap<String, Object>();

		//送“04590501”或者“04590502”
		String bankSystemType = reqBody.get("bankSystemType");
		
		String newPassword = reqBody.get("passwordNew");
		String globalType = reqBody.get("globalType");
		String globalId = reqBody.get("globalId");
		String mobile = reqBody.get("mobile");
		String acctNo = reqBody.get("acctNo");
		
		reqSysHead = RequestMap.getReqSysHead(TransCodeEnum.RETRIEVE_PASSWORD.getServiceCode(), TransCodeEnum.RETRIEVE_PASSWORD.getServiceSence(), "0110");

		//SysHead head = RequestSysHead.getReqSysHead(TransCodeEnum.RETRIEVE_PASSWORD.getServiceCode(), TransCodeEnum.RETRIEVE_PASSWORD.getServiceSence(), "0110");
		
	//RetrievePassword retrievePassword= new RetrievePassword();
		
		
		Map<String, Object> body = new HashMap<String, Object>();
		body.putAll(reqBody);
		
		inputMap = RequestMap.getInputMap(body);
		
		inputMap.put("sendBranchId", bankSystemType);
		
		inputMap.put("sysHead", reqSysHead);
		inputMap.put("newPassword", newPassword);
		inputMap.put("globalType", globalType);
		inputMap.put("globalId", globalId);
		inputMap.put("mobile", mobile);
		inputMap.put("acctNo", acctNo);
		inputMap.put("bankNo", bankSystemType);
		
		
		log.info("找回密码请求开始...");
		Map<String, Object> retrieveResult = EsbConsumerUtil.clientRequest(inputMap);
		log.info("找回密码请求结束 响应结果：{}", retrieveResult);
		String code = retrieveResult.get("code").toString();
		if (!CodeUtil.CODE_200.getCode().equals(code)) {
			switch (code) {
			case BusinessConstant.RESET_PASSWORD_EXCEPTION:
				retrieveResult.put("code", CodeUtil.CODE_10010.getCode());
				break;
			case BusinessConstant.VALIDATION_INVALID_ACCOUNT:
				retrieveResult.put("code", CodeUtil.CODE_10018.getCode());
				break;
			default:
				retrieveResult.put("code", CodeUtil.CODE_99999.getCode());
				break;
			}
			return retrieveResult;
		}
		
		return ResultUtil.resultMap("成功", ResultCode.RESULT_CODE_SUCCESS.code(), null);
	}

	/**
	 * 发送密码
	 */
	@Override
	public Map<String, Object> sendAuthCode(Map<String, String> reqBody) {
		reqBody.put("smsInfo", "您正在进行身份证校验交易");
		return commonService.sendMsgToMB(reqBody);
	}

	/**
	 * 校验验证码
	 */
	@Override
	public Map<String, Object> checkCode(Map<String, String> reqBody) {
		return commonService.verifyCode(reqBody);
	}
	
	/**
	 * 安全退出
	 */
	@Override
	public Map<String, Object> logout(Map<String, String> reqBody) {
		String clientSeqNo = reqBody.get("clientSeqNo").toString();
		RedisUtils.destroyUserInfo(clientSeqNo);
		return ResultUtil.resultMap("成功", ResultCode.RESULT_CODE_SUCCESS.code(), null);
	}
	
	
	public Map<String, Object> pushMsg(Map<String, String> reqBody) {
		Map<String, String> queryMap = new HashMap<>();

		String deviceType = reqBody.get("deviceType");
		String deviceId = reqBody.get("deviceId");

		deviceId = "d432467f01631000a84930300alc254c706";

		String version = reqBody.get("version");
		String network = reqBody.get("network");

		queryMap.put("deviceType", deviceType);
		queryMap.put("deviceId", deviceId);

		queryMap.put("version", version);
		queryMap.put("network", network);
		String userid = "500000040";
		Map<String, Object> resMap = addPushMsg(queryMap, userid);

		return resMap;
	}

}